package org.annoflow.javassist;

import java.util.List;

import javassist.CannotCompileException;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;
import javassist.expr.Expr;

public class InsertAfter extends AbstractCommand
{
//	private class ClassOutline
//	{
//		public Map<String,CtMethod> declaredMethods;
//		public ClassOutline(CtClass myClazz)
//		{
//			declaredMethods = new HashMap<String,CtMethod>();
//			outline(myClazz);
//		}
//		private void outline(CtClass clazz)
//		{
//			//System.out.println("\nAnalyzing "+ clazz.getName());
//			for(CtMethod method : clazz.getDeclaredMethods())
//			{
//				declaredMethods.put(method.getName(), method);
//			}
//		}
//		public boolean isDeclared(String methodName)
//		{
//			if(declaredMethods.get(methodName) == null)
//				return false;
//			return true;
//		}
//	}
//	public static Map<String, ClassOutline> inheritanceMap = new HashMap<String, ClassOutline>();

//	private static boolean rewriteNeeded(CtClass clazz, String methodName)
//	{
//		try
//		{
//			if (clazz != null)
//			{
//				// VM currentVM = VM.currentVM();
//				// ClassOutline cOutline = inheritanceMap.get(clazz.getName());
//				if (VM.currentVM().isLocalClass(clazz.getName()))
//				{
//					for (CtBehavior behavior : clazz.getDeclaredBehaviors())
//					{
//						String behaviorName = behavior.getLongName();
//						if (behaviorName.endsWith(methodName))
//						{
//							return false;
//						}
//					}
//					CtClass superClazz = null;
//					superClazz = clazz.getSuperclass();
//					return rewriteNeeded(superClazz, methodName);
//
//				}
//				else
//				{
//					return true;
//				}
//			}
//		}
//		catch (NotFoundException e)
//		{
//			;
//		}
//		return true;
//	}

	private static boolean inSuperChain(CtClass declaringClass, String superName)
	{
		if (declaringClass != null)
		{
			try
			{
				if (declaringClass.getName().equals(superName))
				{
					return true;
				}
				else
				{
					return inSuperChain(declaringClass.getSuperclass(), superName);
				}
			}
			catch (NotFoundException e)
			{
				;
			}
		}
		return false;
	}

	protected InsertAfter(List<String> argList) throws MalformedCommandException
	{
		super(argList);
	}

	@Override
	public void translate(Expr call, boolean isSuper) throws MalformedCommandException,
			CannotCompileException
	{
		// TODO Auto-generated method stub

	}

	public String getReplacement()
	{
		return unParsedArgs.get(4).substring(1, unParsedArgs.get(4).length() - 1);
	}

	@Override
	public void translate(CtMethod member, String expressionName) throws MalformedCommandException,
			CannotCompileException
	{
		if (expressionName.equals(getSignature())
				&& inSuperChain(member.getDeclaringClass(), unParsedArgs.get(3)))
		{
//			String replacement = getReplacement();
			member.insertAfter(getReplacement());

		}
	}

}
